import type { ReactElement } from 'react';
import React, { useState, useRef, useEffect } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Spin, Tree, message, Button, Tooltip, Form,
  Input,
  Select,
  Row,
  Col,
} from 'antd';
import styles from './index.less';
import { ProCard } from '@ant-design/pro-components';
import FileOpen from '@/components/FileIframOpen';
import ChangePhone from './changePhone'
import {
  getGroupWorkerByGroupIdApi,
  getProjectGroupApi,
  getProjectLaborCompanyApi,
  countWorker,
  getById,
  changePhone
} from '@/services/public';
const FormItem = Form.Item;
// 初始化treeData
const fomatTreeData = (data = []) => {
  const cData = JSON.parse(JSON.stringify(data));
  const nList = cData.map((item: any) => {
    item.title = item.name;
    item.value = item.id ? item.id : item.name;
    item.key = item.id ? item.id : item.name;
    item.selectable = item.children ? false : true;
    // item.icon = item.children ? null : <UserAddOutlined />;
    if (item.children) {
      item.children = fomatTreeData(item.children);
    }
    return item;
  });
  return nList;
};

// 处理班组数据结构
const formatGroupTreeData = (data: any, labourCorpName: any) => {
  const cData = JSON.parse(JSON.stringify(data));
  const nData = cData.map((item: any) => {
    item.id = labourCorpName + '_' + item.id;
    item.isLeaf = true;
    return item;
  });
  return nData;
};



const RegisterList: React.FC<any> = ({ projectInfo, origin }): ReactElement => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const pageRef = useRef<any>(true);
  const [treeLeafInfo, setTreeLeafInfo] = useState<any>({});
  const [departmentList, setDepartmentList] = useState<any>([]);
  const [tableList, setTableList] = useState<any>([]);
  const [fileUrl, setFileUrl] = useState<string>('');
  const [showFile, setShowFile] = useState<boolean>(false);
  const [isSearch, setIsSearch] = useState<boolean>(false)
  const [pageInfo, setPageInfo] = useState<any>({
    total: 0,
    pageSize: 20,
    pageNo: 1,
  });
  const [countWorkerTotal, setCountWorkerTotal] = useState<any>({})
  const [info, setInfo] = useState<any>({});
  const [showVisible, setShowVisible] = useState<boolean>(false);
  const getUrl = async (id: any) => {
    const res = await getById({ id })
    if (res && res.success) {
      setFileUrl(res.data.labourContractFileUrl);
      setShowFile(true);
    } else {
      message.error(res.errMsg || '操作失败');
    }
  };
  const columns: ProColumns<any>[] = [
    {
      title: '姓名',
      dataIndex: 'userName',
      width: 80,
      fixed: 'left',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 80,
      valueEnum: {
        0: { text: '-', status: 0 },
        1: { text: '男', status: 1 },
        2: { text: '女', status: 2 },
      },
    },
    {
      title: '身份证',
      dataIndex: 'userCertNo',
      width: 120,
      render: (_, record) => {
        return <div style={{ wordBreak: 'break-all' }}>{record.userCertNo}</div>;
      },
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
      width: 100,
    },
    // {
    //   title: '工资卡号',
    //   dataIndex: 'salaryNo',
    //   width: 120,
    //   render: (_, record) => {
    //     return <div style={{ wordBreak: 'break-all' }}>{record.salaryNo}</div>;
    //   },
    // },
    // {
    //   title: '工资开户行',
    //   dataIndex: 'salaryAccountBank',
    //   width: 100,
    // },
    {
      title: '人员状态',
      dataIndex: 'workStatus',
      width: 80,
      valueEnum: {
        0: { text: '离职', status: 0 },
        1: { text: '在职', status: 1 },
      },
    },
    {
      title: '工人类型',
      dataIndex: 'workType',
      width: 80,
    },
    {
      title: '岗位/工种',
      dataIndex: 'profession',
      width: 80,
    },
    {
      title: '进场日期',
      dataIndex: 'inWorkDate',
      valueType: 'date',
      width: 100,
    },
    {
      title: '出场日期',
      dataIndex: 'outWorkDate',
      valueType: 'date',
      width: 100,
    },
    {
      title: '所属单位',
      dataIndex: 'labourCorpName',
      width: 100,
    },
    {
      title: '所属班组',
      dataIndex: 'groupName',
      width: 80,
    },
    {
      title: '家庭地址',
      dataIndex: 'address',
      width: 100,
      ellipsis: {
        showTitle: false,
      },
      // render: address => (
      //   <Tooltip placement="topLeft" title={address}>
      //     {address}
      //   </Tooltip>
      // ),
    },

    {
      title: '劳动合同',
      dataIndex: 'labourContractFileId',
      width: 75,
      render: (_, record) => (
        <span>
          {record.labourContractFileId ? (
            <a
              onClick={() => {
                getUrl(record.id)

              }}
            >
              查看
            </a>
          ) : '-'
            //  (
            //   <a
            //     onClick={() => {
            //       setInfoValue(record);
            //       handleContractVisible(true);
            //     }}
            //   >
            //     上传
            //   </a>
            // )
          }
        </span>
      ),
    },
    {
      title: '劳动合同开始日期',
      dataIndex: 'contractStartDate',
      valueType: 'date',
      width: 100,
    },
    {
      title: '劳动合同结束日期',
      dataIndex: 'contractEndDate',
      valueType: 'date',
      width: 100,
    },
    {
      title: '劳动合同签订日期',
      dataIndex: 'contractSignDate',
      valueType: 'date',
      width: 100,
    },
    {
      title: '劳动合同类型',
      dataIndex: 'contractType',
      width: 80,
      valueEnum: {
        1: { text: '固定期限劳动合同', status: 1 },
        2: { text: '无固定期限劳动合同', status: 2 },
        3: { text: '以完成一定工作任务为期限的劳动合同', status: 3 },
        4: { text: '劳务派遣合同', status: 4 },
        9: { text: '其他', status: 9 },
      },
    },
    {
      title: '工资计算方式',
      dataIndex: 'payRollType',
      width: 80,
      valueEnum: {
        1: { text: '按月', status: 1 },
        2: { text: '按周', status: 2 },
        3: { text: '按日', status: 3 },
        4: { text: '按小时', status: 4 },
        5: { text: '计件', status: 5 },
        9: { text: '其他', status: 9 },
      },
    },
    {
      title: '合同单价（元）',
      dataIndex: 'payRollLevel',
      width: 80,
    },
  ];
  // if (origin == 'project') {
  //   columns.push(
  //     {
  //       title: '操作',
  //       dataIndex: 'option',
  //       valueType: 'option',
  //       width: 120,
  //       render: (_, record: any) => (
  //         <>
  //           <a
  //             onClick={() => {
  //               setInfo(record);
  //               setShowVisible(true);
  //             }}
  //           >
  //             更改手机号码
  //           </a>
  //         </>
  //       )
  //     }
  //   )
  // }
  const contractTypeOptions = [
    { label: '未上传', value: -1, key: '-1' },
    { label: '已上传', value: -2, key: '-2' },
    { label: '固定期限劳动合同', value: 1, key: '1' },
    { label: '无固定期限劳动合同', value: 2, key: '2' },
    { label: '以完成一定工作任务为期限的劳动合同', value: 3, key: '3' },
    { label: '劳务派遣合同', value: 4, key: '4' },
    { label: '其他', value: 9, key: '9' },
  ]

  const [treeLoad, setTreeLoad] = useState<boolean>(false);
  const [tableLoad, setTableLoad] = useState<boolean>(false);

  // 人员列表数据
  const queryUserList = async (leafInfo: any, pageIf: any) => {
    if (leafInfo.id) {
      setTableLoad(true);
      const params: any = {};
      const leafIdList = leafInfo.id.split('_');
      params.corpId = projectInfo.corpId;
      params.projectId = projectInfo.projectId;
      params.labourCorpName = leafIdList[0];
      params.pageNo = pageIf.pageNo;
      params.pageSize = pageIf.pageSize;
      params.labourCorpName = leafIdList[0];
      if (leafIdList[leafIdList.length - 1] !== 'null') {
        params.groupId = leafIdList[1];
      }
      setIsSearch(false)
      const response = await getGroupWorkerByGroupIdApi(params);
      setTableLoad(false);
      if (response && response.success) {
        setPageInfo({
          pageNo: pageIf.pageNo,
          pageSize: pageIf.pageSize,
          total: response.total
        })
        setTableList(response.data || []);
        // setPageInfo((page) => {
        // 	page.total = response.total;
        // 	return page;
        // });
      } else {
        message.error(response.errMsg);
      }
    }
  };

  // 班组人员
  const getGroupList = async (labourCorpName: any, departmentL: any, isFirst: boolean) => {
    const response = await getProjectGroupApi({
      corpId: projectInfo.corpId,
      projectId: projectInfo.projectId,
      labourCorpName,
    });
    if (response && response.success) {
      response.data.push({
        id: 'null',
        name: '直属人员',
      });
      const cDepartmentList = JSON.parse(JSON.stringify(departmentL));
      const groupTreeData = formatGroupTreeData(response.data || [], labourCorpName);
      const cList = cDepartmentList.map((item: any) => {
        if (item.name == labourCorpName) {
          item.children = JSON.parse(JSON.stringify(groupTreeData));
        }
        return item;
      });
      if (isFirst) {
        setTreeLeafInfo(groupTreeData[0]);
        queryUserList(groupTreeData[0], pageInfo);
      }
      setDepartmentList(fomatTreeData(cList));
      setTreeLoad(false);
    }
  };

  // 劳务公司数据
  const getDepartmentList = async () => {
    setTreeLoad(true);
    const response = await getProjectLaborCompanyApi({
      corpId: projectInfo.corpId,
      projectId: projectInfo.projectId,
    });
    if (response && response.success) {
      // 获取到劳务公司数据
      const departmentL: any = fomatTreeData(response.data || []);
      // 请求第一个劳务公司下的班组人员
      if (departmentL.length && !departmentL[0].children) {
        const firstTreeLeaf = departmentL[0];
        getGroupList(firstTreeLeaf.key, departmentL, true);
      } else {
        setDepartmentList([]);
        setTreeLoad(false);
      }
    } else {
      message.error(response.errMsg || '请求失败');
    }
  };

  const onLoadData = ({ key, children }: any) => {
    return new Promise<void>((resolve) => {
      if (children) {
        resolve();
        return;
      }
      setTimeout(() => {
        getGroupList(key, departmentList, false);
        resolve();
      }, 1000);
    });
  };

  const handleSelectTree = (selectedKeys: any, e: any) => {
    console.log(pageInfo);
    // setPageInfo((page: any) => {
    //   page.pageNo = 1;
    //   page.pageSize = 20;
    //   return page;
    // });
    setTreeLeafInfo(e.node);
    queryUserList(e.node, { pageNo: 1, pageSize: 20 });
  };

  const handlePageChange = (pageNo: any, pageSize: any) => {
    // setPageInfo((page: any) => {
    //   page.pageNo = pageNo;
    //   page.pageSize = pageSize;
    //   return page;
    // });
    queryUserList(treeLeafInfo, { pageNo, pageSize });
  };
  const toSearch = async () => {
    setTableLoad(true);
    const fieldsValue: any = await form.validateFields();
    // queryUserList({},{})
    let params: any = {
      pageNo: 1,
      pageSize: 20,
      labourCorpName: null,
      userName: fieldsValue?.userName,
      userCertNo: fieldsValue?.userCertNo,
      contractType: fieldsValue?.contractType,
      groupId: -1,
    }
    setIsSearch(true)
    params.corpId = projectInfo.corpId;
    params.projectId = projectInfo.projectId;
    const response = await getGroupWorkerByGroupIdApi(params);
    setTableLoad(false);
    if (response && response.success) {
      setPageInfo({
        pageNo: 1,
        pageSize: 20,
        total: response.total
      })
      setTableList(response.data || []);
      // setPageInfo((page) => {
      // 	page.total = response.total;
      // 	return page;
      // });
    } else {
      message.error(response.errMsg);
    }

  }
  const clear = () => {
    form.resetFields()
    toSearch()
  }

  useEffect(() => {
    getDepartmentList();
    getTotal()
  }, []);

  const titleRender = (nodeData: any) => {
    return <span className={styles.leafTitle}>{nodeData.name}</span>;
  };

  const tProps = {
    treeData: departmentList,
    defaultSelectedKeys: [treeLeafInfo.id],
    defaultExpandedKeys: [departmentList[0] && departmentList[0].key],
    style: {
      width: '100%',
    },
    titleRender: titleRender,
    onSelect: handleSelectTree,
    loadData: onLoadData,
  };

  const expectData = async () => {
    const fieldsValue: any = await form.validateFields();
    const btn = document.createElement('a');
    btn.download = `${projectInfo.projectName || ''} 花名册.xls`;
    let url = `/api/detail/projectGroupWorker/exportExcel?corpId=${projectInfo.corpId}&projectId=${projectInfo.projectId}`;
    if (fieldsValue.userName) {
      url = url + `&userName=${fieldsValue.userName}`
    }
    if (fieldsValue.userCertNo) {
      url = url + `&userCertNo=${fieldsValue.userCertNo}`
    }
    if (fieldsValue.contractType) {
      url = url + `&contractType=${fieldsValue.contractType}`
    }
    btn.href = url
    document.body.appendChild(btn);
    btn.click();
    document.body.removeChild(btn);
  };
  const getTotal = async () => {
    let res = await countWorker({
      projectId: projectInfo.projectId,
      corpId: projectInfo.corpId
    })
    if (res.success) {
      setCountWorkerTotal(res.data)
    }

  }
  const renderTitle = () => {
    return (
      <span>
        花名册总人数:{countWorkerTotal.totals}{' '}
        &nbsp;&nbsp;&nbsp;&nbsp;已上传合同人数:
        {countWorkerTotal.contractTotals}
      </span>
    );
  };
  const handleSubmit = async (values: any) => {
    const hide = message.loading('正在提交中...', 0);
    let res = await changePhone(values)
    setTimeout(hide, 2000);
    if (res && res.success) {
      message.success('更改成功');
      setShowVisible(false);
      setInfo({});
      getDepartmentList();
    } else {
      message.error(res.errMsg);
    }
  }

  return (
    <div className={styles.department}>
      <div className={styles.statistical}>
        {renderTitle()}
      </div>
      <ProCard split="vertical">

        <ProCard colSpan="280px">
          {treeLoad ? (
            <div className={styles.loading}>
              <Spin />
            </div>
          ) : departmentList && departmentList.length ? (
            <Tree {...tProps} />
          ) : (
            '暂无数据'
          )}
        </ProCard>
        <ProCard colSpan="678px">
          <Form
            // layout="inline"
            // {...formItemLayout}
            form={form}
          >
            <Row gutter={24} justify="end">
              <Col span={12} >
                <FormItem label="姓名" name="userName">
                  <Input></Input>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="身份证" name="userCertNo">
                  <Input></Input>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="劳动合同类型" name="contractType">
                  <Select options={contractTypeOptions}  >

                  </Select>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem>
                  <Button type="primary" style={{ marginRight: '10px' }} onClick={toSearch}>搜索</Button>
                  <Button onClick={clear}>重置</Button>
                </FormItem>
              </Col>
            </Row>


            {/* <FormItem>
                
              </FormItem> */}
          </Form>
          <ProTable
            headerTitle={treeLeafInfo.name ? treeLeafInfo.name + '-人员列表' : '人员列表'}
            actionRef={actionRef}
            rowKey="id"
            dataSource={tableList || []}
            columns={columns}
            scroll={{ x: 1500, y: isSearch ? 800 : 10000 }}
            rowSelection={false}
            options={false}
            search={false}
            loading={tableLoad}
            pagination={isSearch ? false : {
              current: pageInfo.pageNo,
              pageSize: pageInfo.pageSize,
              total: pageInfo.total,
              onChange: handlePageChange,
            }}
            toolBarRender={() => [
              <Button size={'small'} type={'primary'} key='export' onClick={expectData}>导出</Button>
            ]}
          />
          {showFile && (
            <FileOpen
              fielUrl={fileUrl}
              modalVisible={showFile}
              onCancel={() => {
                setShowFile(false);
                setFileUrl('');
              }}
            />
          )}
        </ProCard>
      </ProCard>
      {
        showVisible && (
          <ChangePhone
            visible={showVisible}
            cancel={() => {
              setShowVisible(false);
              setInfo({});
            }}
            info={info}
            onSubmit={handleSubmit}
          ></ChangePhone>
        )
      }
    </div>
  );
};

export default RegisterList;
